import { NextApiRequest, NextApiResponse } from "next";
import { SolrResponse } from "~/types/solr";

const SOLR_HOST = process.env.SOLR_HOST as string

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const id = req.query.id as string

  if (req.method === 'GET') {
    const queryParams = new URLSearchParams({ q: `id:${id}` })
    const response = await fetch(`${SOLR_HOST}/solr/promotion_programs/select?${queryParams.toString()}`)
    const data: SolrResponse<any[]> = await response.json()

    if (data.response.numFound === 0) {
      res.status(404).json({ error: 'Program not found' })
      return
    }

    const program = await map(data.response.docs[0])

    res.status(200).json({ data: program })
  }
}

const map = async (program: any) => {
  const data: any = {}

  data.id = program.id
  data.name = program.name_s
  data.start_time = program.start_time_s
  data.end_time = program.end_time_s
  data.applies_to = program.applies_to_s
  data.time_left = (new Date(data.end_time).getTime() - new Date().getTime()) / 1000

  // const duration = moment.duration(data.time_left, 'seconds')
  // const days = duration.days()
  // const hours = duration.hours()
  // const minutes = duration.minutes()
  // const seconds = duration.seconds()

  return data
}